using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using TMS.Application.Common.Interface;
using TMS.Application.Configuration;
using TMS.Infrastructrue.FileService;
using TMS.Infrastructrue.Identity;
using TMS.Infrastructrue.Persistence;
using TMS.Infrastructrue.Repository;

namespace TMS.Infrastructrue
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext<TMSDbContext>(options =>
                options.UseNpgsql(
                    configuration.GetConnectionString("PostgreSQL"),
                    b => b.MigrationsAssembly(typeof(TMSDbContext).Assembly.FullName)));
            
            
            services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>));
            services.AddTransient<IIdentityService, IdentityService>();
            services.AddScoped(typeof(IFileUploadService),typeof(FileUploadService));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                            .AddJwtBearer(option =>
                            {
                                option.RequireHttpsMetadata = false;//配置是否为https协议
                                option.SaveToken = true;//配置token是否保存在api上下文

                                var tokenParameter = configuration.GetSection("JwtSetting").Get<JwtSetting>();
                                option.TokenValidationParameters = new TokenValidationParameters
                                {
                                    ValidateIssuer = true,
                                    ValidateAudience = true,
                                    ValidateLifetime = true,
                                    ValidateIssuerSigningKey = true,

                                    ClockSkew=TimeSpan.FromMinutes(0),//解决token延迟的问题

                                    ValidIssuer = tokenParameter.Issuer,
                                    ValidAudience = tokenParameter.Audience,
                                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret))
                                };
                            });
            return services;
        }
    }
}